package com.feituan.core.service.impl;

import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.feituan.core.persistence.mapper.AdviceMapper;
import com.feituan.core.persistence.mapper.MerchantMapper;
import com.feituan.core.persistence.mapper.UserMapper;
import com.feituan.core.persistence.service.IAdviceService;
import com.feituan.core.pojo.entity.Advice;
import com.feituan.core.pojo.entity.Merchant;
import com.feituan.core.pojo.request.AdvicePageReq;
import com.feituan.core.pojo.response.page.PageData;
import com.feituan.core.service.IAdviceBizService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;

import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

/**
 * @author: liuli
 * @description:
 * @date: 2024/5/9 13:00
 * @since:4.7.9
 **/
@Service
public class AdviceBizServiceImpl implements IAdviceBizService {

    @Autowired
    private IAdviceService adviceService;

    @Autowired
    private AdviceMapper adviceMapper;

    @Autowired
    private MerchantMapper merchantMapper;

    @Autowired
    private UserMapper userMapper;



    @Override
    public PageData<Advice> queryPage(AdvicePageReq request) {
        Page<Advice> page = adviceService.lambdaQuery()
                .eq(!ObjectUtils.isEmpty(request.getStatus()), Advice::getStatus, request.getStatus())
                .eq(!ObjectUtils.isEmpty(request.getUserId()), Advice::getUserId, request.getUserId())
                .page(new Page<>(request.getPage(), request.getLimit()));
        for (Advice record : page.getRecords()) {
            if (record.getMerchantId() != null) {
                Merchant merchant = merchantMapper.selectById(record.getMerchantId());
                if (merchant != null) {
                    record.setMerchantName(merchant.getName());
                }
            }
            record.setUserName(userMapper.selectById(record.getUserId()).getName());
        }

        List<Advice> filteredRecords = page.getRecords().stream()
                .filter(record -> record.getMerchantId() != null)
                .collect(Collectors.toList());

        Page<Advice> filteredPage = new Page<>(request.getPage(), request.getLimit(), page.getTotal());
        filteredPage.setRecords(filteredRecords);

        return PageData.build(filteredPage.getCurrent(), filteredPage.getTotal(), filteredPage.getRecords());
    }

    /**
     * 新增留言板信息
     * @param advice advice
     */
    @Override
    public int saveAdvice(Advice advice) {
        advice.setStatus(0);
        advice.setCreateTime(new Date());
        return this.adviceMapper.insert(advice);
    }

    /**
     * 修改已读未读状态
     * @param id id
     */
    @Override
    public int updateAdvice(Integer id) {
        return this.adviceMapper.updateStatusById(id);
    }
}
